//
//  WBUserAccountViewModel.swift
//  0829-Weibo
//
//  Created by 毕仲阳 on 16/9/1.
//  Copyright © 2016年 mycompany. All rights reserved.
//

import UIKit

class WBUserAccountViewModel: NSObject {

    var account:WBUserAccount?
    static let sharedModel:WBUserAccountViewModel = WBUserAccountViewModel()
    
    //当前用户是否登录
    var userLogin:Bool{
        if account?.access_token != nil && isExpires == false
        {
            return true
        }
        return false
    }
    var isExpires:Bool
    {
        if let expireDate = account?.expiresDate{
            if expireDate.compare(Date()) == .orderedDescending
            {
                return false
            }
        }
        return true
    }
    
    override init() {
        super.init()
        account = self.loadUserAccount()
    }
    // MARK: - 私有方法
    func loadAccessToken(code:String,completion:@escaping (Bool)->())
    {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = [
            "client_id": WB_APPKEY,
            "client_secret": WB_SECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WB_REDIRECT_URI
        ]
        //使用afn发起POST请求
        WBNetworkTools.sharedTools.request(method: .Post, urlString: urlString, parameters: parameters) { (responce, error) in
            if responce == nil || error != nil {
                print("请求错误\(error)")
                completion(false)
                return
            }else
            {
                //print(responce!)
                let account = WBUserAccount(dick: responce! as! [String : Any])
                //
                self.loadUserInfo(account: account, completion: completion)
            }
            
        }
    }
    
    //获取用户的个人信息
    private func loadUserInfo(account:WBUserAccount,completion:@escaping (Bool)->())
    {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = [
            "access_token":(account.access_token ?? ""),
            "uid": (account.uid ?? "")
        ]
        //发起请求
        WBNetworkTools.sharedTools.request(method: .Get, urlString: urlString, parameters: parameters) { (responce, error) in
            if responce == nil || error != nil
            {
                print("请求错误\(error)")
                return
            }
            //print(responce)
            let dict = responce! as! [String : Any]
            account.name = dict["name"]! as? String
            account.profile_image_url = dict["profile_image_url"]! as? String
            account.avatar_large = dict["avatar_large"]! as? String
            self.saveAccount(account: account)
            completion(true)
        }
    }
    //保存用户信息
    ///保存到文件路径
    private func saveAccount(account:WBUserAccount)
    {
        let file = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")
        // 2. 归档
        NSKeyedArchiver.archiveRootObject(account, toFile: file)
    }
    
    //加载用户信息
    private func loadUserAccount()->WBUserAccount?
    {
        let file = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")
        return NSKeyedUnarchiver.unarchiveObject(withFile: file) as? WBUserAccount
    }

}
